<template>
  <Layout>
    <!-- 首页主要内容 -->
    <div class="main-content">
      <div class="content-left">
        <!-- 轮播图区域 -->
        <div class="carousel-section">
          <el-carousel :interval="5000" height="400px">
            <el-carousel-item v-for="item in carouselItems" :key="item.id">
              <div class="carousel-item-content" :style="{ backgroundImage: `url(${item.imageUrl})` }">
                <div class="carousel-caption">
                  <h3>{{ item.title }}</h3>
                  <p>{{ item.description }}</p>
                </div>
              </div>
            </el-carousel-item>
          </el-carousel>
        </div>
        
        <!-- 信息动态区域 -->
        <div class="news-section">
          <div class="section-header">
            <div class="title-wrapper">
              <img src="@/assets/news-icon.png" alt="信息动态" class="news-icon">
              <h3>信息动态</h3>
            </div>
            <router-link to="/media-coverage" class="more-link">更多</router-link>
          </div>
          <div class="news-list">
            <div v-for="(news, index) in newsList" :key="news.id" class="news-item">
              <div class="news-index">{{ index + 1 }}</div>
              <div class="news-tag" v-if="news.isPinned">置顶</div>
              <router-link :to="{ name: 'informationDetail', params: { id: news.id } }"  class="news-title">{{ news.title }}</router-link>
              <div class="news-date">{{ formatDate(news.publishTime) }}</div>
            </div>
            <div v-if="newsList.length === 0" class="no-data">暂无数据</div>
          </div>
        </div>
      </div>

      <!-- 右侧功能面板 -->
      <div class="function-panel">
        <div class="welcome-title">
          <h3>欢迎进入</h3>
          <h2>校园志愿服务系统</h2>
        </div>
        
        <div class="panel-sections">
          <template v-if="loginType === 'user'">
            <div class="panel-section volunteer">
              <div class="section-header">
                <h4>志愿者</h4>
              </div>
              <div class="section-buttons">
                <el-button @click="router.push('/personal-center')">我参与的志愿项目</el-button>
                <el-button @click="router.push('/personal-center')">我加入的志愿队伍</el-button>
              </div>
            </div>
          </template>

          <template v-else-if="loginType === 'organizations'">
            <div class="panel-section team">
              <div class="section-header">
                <h4>志愿队伍</h4>
              </div>
              <div class="section-buttons">
                <el-button @click="router.push('/organization-center')">队伍信息</el-button>
                <el-button>评价志愿者</el-button>
                <el-button @click="router.push('/activateAdd')">发布志愿服务项目</el-button>
                <!-- <el-button>培训信息</el-button> -->
              </div>
            </div>
          </template>

          <template v-else>
            <div class="panel-section seeker">
              <div class="section-header">
                <h4>求助者</h4>
              </div>
              <div class="section-buttons">
                <el-button type="primary" @click="handleRegisterClick('volunteers')">注册成为志愿者</el-button>
                <el-button type="primary" @click="handleRegisterClick('organizations')">注册成为志愿服务队伍</el-button>
              </div>
            </div>
          </template>
        </div>
      </div>
    </div>
  </Layout>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessageBox } from 'element-plus'
import Layout from '@/components/Layout.vue'
import axios from 'axios'

const router = useRouter()
const route = useRoute()
const loginType = ref(localStorage.getItem('type')) // 从 localStorage 获取登录类型

const carouselItems = ref([])

// 获取轮播图数据
const fetchCarousel = async () => {
  try {
    const response = await axios.get('http://localhost:9090/carousel/list')
    if (response.status === 200) {
      // 按sortOrder排序
      const sortedCarousel = response.data.sort((a, b) => a.sortOrder - b.sortOrder)
      carouselItems.value = sortedCarousel.map(item => ({
        id: item.id,
        imageUrl: item.imageUrl,
        title: item.title, // 可以从后端添加这些字段
        description: item.desciption // 可以从后端添加这些字段
      }))
    }
  } catch (error) {
    console.error('获取轮播图失败:', error)
  }
}

const newsList = ref([])

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 获取信息动态数据
const fetchNews = async () => {
  try {
    const response = await axios.get('/api/infotice/all')
    console.log('API响应:', response.data) // 调试日志
    console.log('API响应:', response.status) // 调试日志
    if(response.status === 200 && response.data) {
      // 对数据进行排序：置顶优先，然后按时间倒序
      const sortedNews = response.data.sort((a, b) => {
        if(a.isPinned !== b.isPinned) {
          return b.isPinned - a.isPinned
        }
        return new Date(b.publishTime) - new Date(a.publishTime)
      })
      console.log('排序后的新闻列表:', sortedNews) // 调试日志
      // 只取前7条
      newsList.value = sortedNews.slice(0, 7)
      console.log('处理后的新闻列表:', newsList.value) // 调试日志
    }
  } catch (error) {
    console.error('获取信息动态失败:', error)
  }
}

onMounted(() => {
  fetchNews()
  fetchCarousel()
})

// 检查表单是否有内容
const checkFormContent = () => {
  const form = JSON.parse(localStorage.getItem('registerFormData') || '{}')
  return Object.values(form).some(value => value !== '')
}

// 处理注册点击
const handleRegisterClick = async (type) => {
  // 如果当前在注册页面且有表单内容
  if (route.path === '/register' && checkFormContent()) {
    try {
      await ElMessageBox.confirm(
        '当前页面信息未保存，切换将丢失已填写的信息，是否继续？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
      // 用户点击确定，清空表单并更新类型
      localStorage.removeItem('registerFormData')
      localStorage.setItem('loginTable', type)
      // 如果点击的是当前类型，刷新页面
      if (type === localStorage.getItem('loginTable')) {
        router.go(0)
      } else {
        // 如果是切换到其他类型，先回到首页再进入注册页
        await router.push('/home')
        router.push('/register')
      }
    } catch {
      // 用户点击取消，不做任何操作
      return
    }
  } else {
    // 没有表单内容，直接处理
    localStorage.setItem('loginTable', type)
    router.push('/register')
  }
}

</script>

<style scoped>
/* 主要内容区域样式 */
.main-content {
  max-width: 1200px;
  margin: 20px auto;
  display: flex;
  gap: 20px;
}

/* 内容左侧区域样式 */
.content-left {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 轮播图区域样式 */
.carousel-section {
  flex: 1;
  height: 400px;
  overflow: hidden;
  margin-bottom: 20px;
}

/* 轮播图内容样式 */
.carousel-item-content {
  width: 100%;
  height: 100%;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  position: relative;
}

/* 新闻区域样式 */
.news-section {
  width: 810px;
  background: #fff;
  padding: 20px;
  border-radius: 4px;
}

/* 新闻区域样式 */
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

/* 标题样式 */
.title-wrapper {
  display: flex;
  align-items: center;
  gap: 10px;
}

/* 新闻图标样式 */
.news-icon {
  width: 24px;
  height: 24px;
}

/* 新闻区块标题样式 */
.section-header h3 {
  font-size: 20px;
  margin: 0;
  color: #333;
}

/* "更多"链接样式 */
.more-link {
  color: #e31436;
  text-decoration: none;
  font-size: 14px;
}

/* 新闻列表容器样式 */
.news-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

/* 单条新闻项目样式 */
.news-item {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 14px;
  color: #333;
}

/* 新闻序号样式 */
.news-index {
  width: 24px;
  height: 24px;
  background: #f0f0f0;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #666;
}

/* 新闻标签样式 */
.news-tag {
  background: #e31436;
  color: white;
  padding: 2px 6px;
  border-radius: 2px;
  font-size: 12px;
}

/* 新闻标题样式 */
.news-title {
  color: #333;
  text-decoration: none;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 新闻日期样式 */
.news-date {
  color: #999;
  white-space: nowrap;
}

/* 前三个序号使用红色背景 */
.news-item:nth-child(-n+3) .news-index {
  background: #e31436;
  color: white;
}

/* 功能面板样式 */
.function-panel {
  width: 300px;
  background: #fff;
  border-radius: 4px;
  padding: 15px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

/* 欢迎标题样式 */
.welcome-title {
  text-align: center;
  margin-bottom: 15px;
}

/* 欢迎标题h3样式 */
.welcome-title h3 {
  font-size: 16px;
  color: #333;
  margin: 0;
}

/* 欢迎标题h2样式 */
.welcome-title h2 {
  font-size: 20px;
  color: #e31436;
  margin: 5px 0;
}

/* 面板区域样式 */
.panel-sections {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

/* 单个面板区域样式 */
.panel-section {
  border-bottom: 1px solid #eee;
  padding-bottom: 15px;
}

/* 最后一个面板区域样式 */
.panel-section:last-child {
  border-bottom: none;
}

/* 区域标题h4样式 */
.section-header h4 {
  font-size: 16px;
  color: #333;
  margin: 0 0 10px 0;
}

/* 区域按钮组样式 */
.section-buttons {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

/* 区域按钮基础样式 */
.section-buttons .el-button {
  width: 100%;
  margin: 0;
  height: 32px;
}

/* 主要按钮样式 */
.section-buttons .el-button--primary {
  background-color: #e31436;
  border-color: #e31436;
}

/* 主要按钮悬停样式 */
.section-buttons .el-button--primary:hover {
  background-color: #f02849;
  border-color: #f02849;
}

/* 次要按钮样式 */
.section-buttons .el-button:not(.el-button--primary) {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #606266;
}

/* 次要按钮悬停样式 */
.section-buttons .el-button:not(.el-button--primary):hover {
  color: #e31436;
  border-color: #e31436;
}

/* 响应式布局样式 */
@media (max-width: 768px) {
  .main-content {
    flex-direction: column;
  }
  
  .function-panel {
    width: 100%;
  }
}

/* 轮播图标题区域样式 */
.carousel-caption {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20px;
  background: linear-gradient(to top, rgba(0,0,0,0.7), transparent);
  color: white;
}

/* 轮播图标题样式 */
.carousel-caption h3 {
  margin: 0;
  font-size: 24px;
  margin-bottom: 8px;
}

/* 轮播图描述文字样式 */
.carousel-caption p {
  margin: 0;
  font-size: 16px;
  opacity: 0.9;
}

/* Element Plus 轮播图自定义样式 */
:deep(.el-carousel__container) {
  height: 100%;
}

/* 轮播图项目样式 */
:deep(.el-carousel__item) {
  height: 100%;
}

/* 轮播图箭头样式 */
:deep(.el-carousel__arrow) {
  background-color: rgba(0, 0, 0, 0.3);
}

/* 轮播图指示器样式 */
:deep(.el-carousel__indicators) {
  bottom: 20px;
}

/* 轮播图按钮样式 */
:deep(.el-carousel__button) {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.7);
}

/* 无数据提示样式 */
.no-data {
  text-align: center;
  color: #999;
  padding: 20px 0;
}
</style>
